let ALY = require('aliyun-sdk');
let cdn = new ALY.CDN({
    accessKeyId: "3LJGB0ZPDCYmBd1K",
    secretAccessKey: "OZz52dLvAE0lk1Y2XhthczgKrSe3va",
    endpoint: 'https://cdn.aliyuncs.com',
    apiVersion: '2014-11-11'
});
let request = require('request')

module.exports = function(app,co){
	app.route('/cdn/aliRefresh')
	.get(function(req,res){
		let arr = req.query.val ? req.query.val.split('|'):[];
		let len = arr.length;
		let promises = [];
		co(function*(){
			arr.forEach((url,idx)=>{
				// 细粒度控制
				let type = url.lastIndexOf('/') == (url.length - 1)? 'Directory':'File';
				let p = new Promise((resolve,reject) =>{
					cdn.refreshObjectCaches({
					  ObjectType: type,
					  ObjectPath: url
					},(err,cdnRes)=>{
						if(err){
							reject({
								code:400, // 这里要改造成配置的
								res:err,
								url:url
							})
						}else{
							resolve({
								code:200,
								res:cdnRes,
								url:url
							})
						}
					})
				})
				promises.push(p);
			});	
			let results = yield promises;
			commAfterRequest(results,res);
		})
	});
	app.route('/cdn/dlRefresh')
	.get(function(req,res){
		// console.log(req.query.val);
		let arr = req.query.val?req.query.val.split('|'):[];
		let len = arr.length;
		if(len){
			directoryArr = [];
			fileArr = [];
			for (let i = 0; i < arr.length; i++) {
				if (arr[i]!= ''){
					(arr[i].lastIndexOf('/') == (arr[i].length - 1))?  directoryArr.push(arr[i]):fileArr.push(arr[i]);
				}
			}
			let directoryUrl = '';
			let fileUrl = '';
			let finalUrlArr = [];
			// 比较奇葩的是帝联的规则type=0 或者 type=1 只能带一组(由","分割的字符串)文件夹目录 or 文件目录
			if(directoryArr.length){
				for (let i = 0; i < directoryArr.length; i++) {
					directoryUrl += (directoryArr[i] + ',')
				}
				directoryUrl = directoryUrl.substr(0,directoryUrl.length-1)+'|0';
				finalUrlArr.push(directoryUrl);
			}
			if(fileArr.length){
				for (let i = 0; i < fileArr.length; i++) {
					fileUrl += (fileArr[i]+ ',')
				}
				fileUrl = fileUrl.substr(0,fileUrl.length-1)+'|1';
				finalUrlArr.push(fileUrl);
			}
			co(function*(){
				let promises = [];
				finalUrlArr.forEach((url,idx)=>{
					let tmp = url.split('|');
					let tmpUrl = tmp[0];
					let tmpType = tmp[1];
					let finalUrl = conf.cdn.dl.url+'?captcha='+conf.cdn.dl.captcha+'&url='+tmpUrl+'&type='+tmpType;
					let p = new Promise((resolve,reject)=>{
						request(finalUrl,(err,res,body)=>{
							if(err){
								reject({
									code:400,
									url:finalUrl,
									res:res,
									err:err,
									body:body
								})
							}else{
								resolve({
									code:200,
									url:finalUrl,
									res:res,
									body:body
								})
							}
						})
					})
					promises.push(p);
				})
				let results = yield promises;
				commAfterRequest(results,res);		
			})
		}
	})
}

let commAfterRequest = (arr,res)=>{
	let err = [];
	arr.forEach((ele,idx)=>{
		if(ele.code!=200){
			err.push(ele.url);
		}
	});
	res.json({
		code: err.length?400:200,
		err:err
	})
}






